package com.wawu.server.dao;



import com.wawu.common.annotation.IOC.component.Repository;
import com.wawu.common.exception.BaseException;
import com.wawu.common.utils.SQLBuilder.SelectSQLBuilder;
import com.wawu.common.utils.SQLExcutorUtil;
import com.wawu.pojo.entity.Message;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository
public class MessagesDAO {

    /**
     * 根据商品id查询提问
     * @param goodsId
     * @return
     * @throws SQLException
     */
    public List<Message> getByGoodsId(Long goodsId) throws SQLException {
        SelectSQLBuilder sqlBuilder=new SelectSQLBuilder("messages")
                .addDynamicCondition("goodsId","=", goodsId)
                .addOrderBy("createtime","DESC");
        return SQLExcutorUtil.queryList(sqlBuilder.getSQL(),Message.class,sqlBuilder.getParams());
    }

    /**
     * 插入商品问答
     * @param message
     * @throws SQLException
     */
    public void insert(Message message) throws SQLException {
        String sql = "INSERT INTO messages (userId,goodsId,content,createtime) values(?,?,?,?)";
        ArrayList<Object> params = new ArrayList<>();
        params.add(message.getUserId());
        params.add(message.getGoodsId());
        params.add(message.getContent());
        params.add(message.getCreatetime());

        try {
            int rowsAffected = SQLExcutorUtil.update(sql,params.toArray());
            if (rowsAffected == 0) {
                throw new BaseException("插入失败");
            }
        } catch (SQLException e) {
            throw new BaseException("数据库更新操作失败"+e);
        }
    }

}
